<!--
 * @Date: 2023-04-29 17:52:37
 * @LastEditTime: 2023-06-22 22:23:53

 * 介绍:
-->
<script lang="ts" setup generic="D extends object = AnyObject">
import { PickerConfirmEventParams } from "vant";
import { useRpopupRef } from "../Rpopup";
const props = defineProps<{
  pickerData: Array<D>;
  defaultElect?: (d: D) => boolean;
}>();

/**picker选择器弹窗 */
const RpopupRef = useRpopupRef();

const pickerData = computed(() =>
  props.pickerData.map((v, k) => {
    const defaultElect = props.defaultElect;
    if (defaultElect) {
      if (defaultElect(v)) electIndex.value = k;
    }
    return {
      ...v,
      value: k,
    };
  })
);

const electIndex = ref(0);
const elect = computed(() => pickerData.value[electIndex.value]);

function open() {
  RpopupRef.value?.open();
}
function close() {
  RpopupRef.value?.close();
}

const show = computed({
  get() {
    return RpopupRef.value?.show;
  },
  set(v) {
    if (!RpopupRef.value) return;
    RpopupRef.value.show = v || false;
  },
});

defineExpose({ open, close, show, elect, electIndex });

const emit = defineEmits<{
  (e: "confirm", v: D): void;
}>();

//*切换
function onPickerConfirm(e: PickerConfirmEventParams) {
  const index = e.selectedIndexes.at(0)!;
  electIndex.value = index;
  const _elect = elect.value!;
  emit("confirm", _elect);
  close();
}
</script>
<template>
  <div @click="open" class="RpopupPicker">
    <slot name="left-content" v-bind="({ ...elect } as Partial<D>)"></slot>
    <van-icon
      :class="{ rotate: show }"
      class="transition ML-xs"
      name="arrow-down"
    />
    <slot name="right-content" v-bind="({ ...elect } as Partial<D>)"></slot>
    <Rpopup ref="RpopupRef" :position="'bottom'">
      <van-picker
        :model-value="[electIndex]"
        @confirm="onPickerConfirm"
        @cancel="close"
        :title="$t('qing-xuan-ze')"
        :columns="pickerData"
      >
        <template #option="option: D">
          <slot name="option" v-bind="{ ...option }">{{ option }}</slot>
        </template>
      </van-picker>
    </Rpopup>
  </div>
</template>
<style lang="scss" scoped>
.rotate {
  transform: rotate(180deg);
}
.transition {
  transition: all 200ms linear;
}
</style>
